package easy.trace.plugin.springmvc;

import easy.trace.plugin.springmvc.utils.RequestHelper;
import easy.trace.common.Span;
import easy.trace.core.common.Constants;
import easy.trace.core.context.TraceContext;
import easy.trace.core.dto.TransferParams;

import javax.servlet.http.HttpServletRequest;

import java.util.Optional;

/**
 * @author easy
 */
public class HttpRequestContext implements TraceContext {
    private HttpServletRequest request;
    private static final String EVENT_TYPE_SPRINGMVC = "SPRINGMVC";
    private static final String EVENT_TYPE_HOMEPAGE = "HOMEPAGE";
    private boolean homePageFlag = true;


    public HttpRequestContext(HttpServletRequest request) {
        this.request = request;
        this.homePageFlag = !RequestHelper.containsTraceHeader(request);
    }

    @Override
    public String getServiceId() {
        return RequestHelper.replaceURL(request);
    }

    @Override
    public String getMethod() {
        return "";
    }

    @Override
    public String getEventType() {
        if (homePageFlag) {
            return EVENT_TYPE_HOMEPAGE;
        }
        return EVENT_TYPE_SPRINGMVC;
    }

    @Override
    public boolean isCaller() {
        if (homePageFlag) {
            return false;
        }
        return true;
    }

    @Override
    public boolean isCalled() {
        return !this.isCaller();
    }

    @Override
    public int port() {
        return request.getRemotePort();
    }

    @Override
    public String address() {
        return request.getRemoteAddr();
    }

    @Override
    public TransferParams getTransferParams() {
        TransferParams transferParams = new TransferParams();

        transferParams.isExistTraceHeader(!homePageFlag);

        if (!homePageFlag) {
            Optional.ofNullable(request.getHeaders(Constants.TRACE_ID.toLowerCase())).ifPresent((traceId) -> transferParams.setTraceId(Long.valueOf(traceId.nextElement())));
            Optional.ofNullable(request.getHeaders(Constants.PARENT_ID.toLowerCase())).ifPresent((parentId) -> transferParams.setParentId(Long.valueOf(parentId.nextElement())));
            Optional.ofNullable(request.getHeaders(Constants.SPAN_ID.toLowerCase())).ifPresent((spanId) -> transferParams.setSelfId(Long.valueOf(spanId.nextElement())));
        }
        return transferParams;
    }

    @Override
    public void setTransferParams(Span span) {
        /*try {
            System.out.println("setTransferParams");
            request.setAttribute(Constants.TRACE_ID.toLowerCase(), span.getTraceId());
            request.setAttribute(Constants.PARENT_ID.toLowerCase(), span.getParentId());
            request.setAttribute(Constants.SPAN_ID.toLowerCase(), span.getId());
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }*/
    }

}
